<script setup>
import {useRoute} from "vue-router";
import {get, post} from "@/net"
import {reactive, ref} from "vue";
import router from "@/router";
import {
    Male,
    Female, ArrowLeft, CircleCheck, Star, EditPen, Plus, ChatSquare, Delete
} from "@element-plus/icons-vue";
import {QuillDeltaToHtmlConverter} from 'quill-delta-to-html';
import Card from "@/components/Card.vue";
import TopicTag from "@/components/TopicTag.vue";
import InteractButton from "@/components/InteractButton.vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {useStore} from "@/store";
import TopicEditor from "@/components/TopicEditor.vue";
import TopicCommentEditor from "@/components/TopicCommnetEditor.vue";

const route = useRoute()
const store = useStore()
const tid = route.params.tid
const topic = reactive({
    data: null,
    like: false,
    collect: false,
    comments: null,
    page: 1
})

const edit = ref(false)
const init = () => get(`/api/forum/topic?tid=${tid}`, data => {
    topic.data = data
    topic.like = data.interact.like
    topic.collect = data.interact.collect
    loadComments(1)
})
init()

function ConvertToHtml(content) {
    const ops = JSON.parse(content).ops
    const converter = new QuillDeltaToHtmlConverter(ops, {inlineStyles: true});
    return converter.convert();
}

function interact(type, message) {
    get(`/api/forum/interact?tid=${tid}&type=${type}&state=${!topic[type]}`, () => {
        topic[type] = !topic[type]
        if (topic[type])
            ElMessage.success(`${message}成功`)
        else
            ElMessage.success(`${message}取消成功`)

    })
}

function updateTopic(editor) {
    post(`/api/forum/update-topic`, {
        id: tid,
        type: editor.type.id,
        title: editor.title,
        content: editor.text
    }, () => {
        ElMessage.success('帖子更新成功')
        edit.value = false
        init()
    })
}

const comment = reactive({
    show: false,
    text: '',
    quote: null
})

function loadComments(page) {
    topic.comments = null
    topic.page = page
    get(`/api/forum/comments?tid=${tid}&page=${page - 1}`, data => {
        topic.comments = data
    })
}

function onCommentAdd() {
    comment.show = false
    loadComments(Math.floor(++topic.data.comments / 10) + 1)
}

function deleteComment(id) {
    get(`/api/forum/delete-comment?cid=${id}`, () => {
        ElMessage.success('删除成功')
        loadComments(topic.page)
    })
}
const deleteTopic = async (id) => {
    try {
        await ElMessageBox.confirm(
            '确认要删除这个帖子吗？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                customClass: 'custom-delete-dialog' // 添加自定义类名
            }
        );
        // 用户点击确定后执行删除操作
        get(`/api/forum/delete-topic?tid=${id}`, () => {
            ElMessage.success('删除帖子成功,跳转首页');
            router.push('/index');
        });
    } catch (error) {
        // 用户点击取消，不执行删除操作
        ElMessage.success('取消删除');
    }
};
</script>
<template>
    <div class="topic-page" v-if="topic.data">
        <div class="topic-main" style="position: sticky;top: 0 ;z-index: 10">
            <card style="display: flex;width: 100%">
                <el-button :icon="ArrowLeft" type="info" size="small"
                           plain round @click="router.push('/index');">返回列表
                </el-button>
                <div style="text-align: center;flex: 1">
                    <topic-tag :type="topic.data.type" style="margin-right: 80px"></topic-tag>
                    <span style="font-weight: bold;">
                        {{ topic.data.title }}
                    </span>
                </div>
            </card>
        </div>
        <div class="topic-main">
            <div class="topic-main-left">
                <el-avatar :src="store.avatarUserUrl(topic.data.user.avatar)"
                           :size="60"/>
                <div>
                    <div style="font-weight: bold;font-size: 18px">
                        {{ topic.data.user.username }}
                        <span style="color: hotpink" v-if="topic.data.user.gender===1">
                            <el-icon style="margin-right:3px;translate: 0 2px"><Female/></el-icon>
                        </span>
                        <span style="color: dodgerblue" v-if="topic.data.user.gender === 0">
                            <el-icon style="margin-right:3px;translate: 0 2px"><Male/></el-icon>
                        </span>
                        <div class="desc">{{ topic.data.user.email }}</div>

                    </div>
                    <el-divider style="margin: 10px 0px 10px 0"/>
                    <div style="text-align: left; margin: 0 5px">
                        <div class="desc">微信号: {{ topic.data.user.wx || '已经隐藏或者未填写' }}</div>
                        <div class="desc">qq号: {{ topic.data.user.qq || '已经隐藏或者未填写' }}</div>
                        <div class="desc">手机号: {{ topic.data.user.phone || '已经隐藏或者未填写' }}</div>
                    </div>
                    <el-divider style="margin: 10px 0px 10px 0"/>
                </div>
                <div class="desc" style="margin: 0 5px;text-align: justify;">
                    {{ topic.data.user.desc }}
                </div>
            </div>
            <div class="topic-main-right">
                <div class="topic-content" v-html="ConvertToHtml(topic.data.content)"></div>
                <el-divider/>
                <div style="font-size: 13px;color: grey;text-align: center;">
                    <div>发表于 {{ new Date(topic.data.time).toLocaleString() }}</div>

                </div>
                <div style="text-align: right;margin-top: 30px">
                    <interact-button name="删除帖子"  color="red" :check="topic.collect"
                                     style="margin-right: 30px"
                                     @check="deleteTopic(tid)" v-if="topic.data.user.id===store.user.id">
                        <el-icon color="red">
                            <Delete/>
                        </el-icon>
                    </interact-button>
                    <interact-button name="编辑一下" color="dodgerblue" :check="false"
                                     @check="edit=true" style="margin-right: 30px"
                                     v-if="store.user.id===topic.data.user.id">
                        <el-icon >
                            <EditPen/>
                        </el-icon>
                    </interact-button>
                    <interact-button name="点个赞吧" check-name="已点赞" color="pink" :check="topic.like"
                                     @check="interact('like','点赞') ">
                        <el-icon>
                            <CircleCheck/>
                        </el-icon>
                    </interact-button>
                    <interact-button name="收藏一下吧" check-name="已收藏" color="orange" :check="topic.collect"
                                     style="margin-left: 30px"
                                     @check="interact('collect','收藏')">
                        <el-icon>
                            <Star/>
                        </el-icon>
                    </interact-button>
                </div>
            </div>

        </div>
        <transition name="el-fade-in-linear" mode="out-in">
            <div v-if="topic.comments">
                <div class="topic-main" style="margin-top: 10px" v-for="item in topic.comments">
                    <div class="topic-main-left">
                        <el-avatar :src="store.avatarUserUrl(item.user.avatar)"
                                   :size="60"/>
                        <div>
                            <div style="font-weight: bold;font-size: 18px">
                                {{ item.user.username }}
                                <span style="color: hotpink" v-if="item.user.gender===1">
                            <el-icon style="margin-right:3px;translate: 0 2px"><Female/></el-icon>
                        </span>
                                <span style="color: dodgerblue" v-if="item.user.gender === 0">
                            <el-icon style="margin-right:3px;translate: 0 2px"><Male/></el-icon>
                        </span>
                                <div class="desc">{{ item.user.email }}</div>

                            </div>
                            <el-divider style="margin: 10px 0px 10px 0"/>
                            <div style="text-align: left; margin: 0 5px">
                                <div class="desc">微信号: {{ item.user.wx || '已经隐藏或者未填写' }}</div>
                                <div class="desc">qq号: {{ item.user.qq || '已经隐藏或者未填写' }}</div>
                                <div class="desc">手机号: {{ item.user.phone || '已经隐藏或者未填写' }}</div>
                            </div>
                        </div>

                    </div>
                    <div class="topic-main-right">
                        <div style="font-size: 13px;color: grey;">
                            <div>评论时间:{{ new Date(item.time).toLocaleString() }}</div>
                        </div>
                        <div v-if="item.quote" class="comment-quote">
                            回复：{{ item.quote }}
                        </div>

                        <div class="topic-content" v-html="ConvertToHtml(item.content)"></div>
                        <div style="text-align: right">
                            <el-link :icon="ChatSquare" @click="comment.show=true; comment.quote=item" type="info">
                                &nbsp;回复评论
                            </el-link>

                            <!-- 仅当当前用户是评论的作者时显示删除按钮 -->
                            <el-link
                                :icon="Delete"
                                type="danger"
                                v-if="item.user.id===store.user.id"
                                style="margin-left: 20px"
                                @click="deleteComment(item.id)">
                                &nbsp;删除评论
                            </el-link>
                        </div>
                    </div>
                </div>
                <div style="width: fit-content;margin: 20px auto;">
                    <el-pagination background layout="prev, pager, next"
                                   v-model:current-page="topic.page"
                                   @current-change="loadComments"
                                   :total="topic.data.comments"
                                   :page-size="10" hide-on-single-page>
                    </el-pagination>
                </div>
            </div>

        </transition>
        <TopicEditor :show="edit" @close="edit=false" v-if="topic.data&& store.forum.types"
                     :default-type="topic.data.type"
                     :default-title="topic.data.title"
                     :default-text="topic.data.content"
                     defaultButton="更新帖子" :submit="updateTopic"/>
        <TopicCommentEditor :show="comment.show" @close="comment.show=false" :tid="tid"
                            :quote="comment.quote" @comment="onCommentAdd"/>
        <div>

            <div class="add-comment" @click="comment.show=true;comment.quote=null">
                <span class="pl-class">点击评论</span>
                <elicon>
                    <Plus/>
                </elicon>
            </div>
        </div>
    </div>
</template>


<style scoped>
.comment-quote {
    font-size: 13px;
    color: grey;
    background-color: rgba(94, 94, 94, 0.1);
    padding: 10px;
    margin-top: 10px;
    border-radius: 5px;
}
.pl-class{
    position: fixed;
    bottom: 38px;
    right: 70px;
    width: 80px;
    height: 40px;
    font-size: 20px;
    color: var(--el-color-primary);
}
.pl-class:hover {
    cursor: pointer;
    background: var(--el-border-color-extra-light);
}
.add-comment {
    position: fixed;
    bottom: 40px;
    right: 20px;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    font-size: 18px;
    color: var(--el-color-primary);
    text-align: center;
    line-height: 45px;

    background: var(--el-bg-color-overlay);
    box-shadow: var(--el-box-shadow-lighter);

}

.add-comment:hover {
    cursor: pointer;
    background: var(--el-border-color-extra-light);
}

.topic-page {
    display: flex;
    flex-direction: column;
    gap: 10px;
    padding: 10px 0;
}

.topic-main {
    display: flex;
    border-radius: 7px;
    margin: 0 auto;
    background-color: var(--el-bg-color);
    width: 1100px;
}

.topic-main-left {
    width: 300px;
    padding: 10px;
    text-align: center;
    border-right: solid 1px var(--el-border-color);

}

.desc {
    font-size: 12px;
    color: grey;
}

.topic-main-right {
    width: 800px;
    padding: 10px 20px;
    display: flex;
    flex-direction: column;
}

.topic-content {
    font-size: 14px;
    opacity: 0.8;
    line-height: 22px;
    flex: 1;
}

</style>